import sys
import time
from os.path import expanduser
import yaml
import socket
import random
from command import commandParser
import zomlog

class Config(object):
    def __init__(self, password_file):
        file = open(expanduser(password_file), "r")
        passw = file.read().replace("\n", "")
        file.close; del file
        self.passw = passw
        self.user = "Zombot"
        self.nick = "zombot"
        self.host = "irc.freenode.net"
        self.port = 6667
        self.chans = {
             "masterchan":"#testwiki"
             "opschan"   :"#testwiki-ops"
             "mainchan"  :"#testwiki-zombies"
             "devchan"   :"#testwiki-zombie-dev"
             "buggiechan":"#testwiki-zombie-bugs"
        }
        self.debug = True
        self.ident = "zombot"
        self.realname = "Zombot IRC Gaming Bot v1.0.5"

class botHandler(object):
    def run(self):
        while 1:
            try:
                self.main()
            except Exception:
                pass
            time.sleep(15)
    def main(self):
        self.config = Config("/home/ceradon/password.txt")
        sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
        sock.connect( ( self.config.host, self.config.port ) )
        
        while True:
            data = sock.recv(2048)
            raw = data.split(" ")
            if raw[1].find("NOTICE") != -1:
                if raw[2].find("AUTH") != -1:
                    if raw[0].find(":*** Looking up your hostname") != -1:
                        #Start authentication.
                        self.sendraw("NICK %s\n") % self.config.nick
                        self.sendraw("USER %s %s bla :%s\n") % (self.config.user, self.config.host, self.config.realname)
                        
            if raw[1].find("433") != -1:
                #Our nick is in use.
                rand = random.randrange(0, 100)
                self.config.nick = self.config.nick+"-"+rand
                self.sendraw("NICK %s\n") % self.config.nick
                #Alert the program executer:
                print "Now connected to %s:%s as %s. Signed in as %s" % (self.config.host, self.config.port, self.config.nick, self.config.user)
                
            elif raw[1].find("376") !=  -1:
                #End of the MOTD
                self.sendraw("NICKSERV IDENTIFY %s %s") % (self.config.nick, self.config.passw)
                for channel in self.config.chans:
                    self.joinchan(channel)
                commandParser.Start()
    
    def sendraw(self, message):
        sock.send(message)
    
    def joinchan(self, channel)
        self.channel = channel
        self.sendraw("JOIN %s\n") % channel
        zomlog.write_log("Joined %s\n)
        
    def partchan(self, channel):
        if channel != "":
           self.channel = channel
        else:
           self.
